package com.ilvyou.api.controller;

import com.ilvyou.api.common.Cache;
import com.ilvyou.api.common.Constant;
import com.ilvyou.api.bean.result.Result;
import com.ilvyou.api.common.LoginInterceptor;
import com.ilvyou.api.service.PersonalService;
import com.ilvyou.api.service.UserService;
import com.ilvyou.api.service.ZanService;
import com.ilvyou.api.util.RemoteUtil;
import com.ilvyou.core.util.StringUtil;
import com.ilvyou.data.lhf.ScrAlipayEntity;
import com.ilvyou.data.lhf.ScrQuestionEntity;
import com.ilvyou.data.lhf.SrcAuthbaseEntity;
import com.ilvyou.data.lvzan.AppUserEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by GuanYuCai on 16/9/16.
 */
@Controller
public class PersonalController extends BaseController{

    private Logger log = Logger.getLogger(PersonalController.class);

    @Autowired
    private PersonalService personalService;
    @Autowired
    private UserService userService;
    @Autowired
    private ZanService zanService;

    @RequestMapping(value = "/personal/questionSubmit", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> submitQuestion(@RequestParam Long questionid, @RequestParam String answer,
                                         @RequestParam String token, @RequestParam String uuid) throws Exception {
        Cache.User user = Cache.get(token);
        if (user == null){
            log.debug("token " + token + " invalid!");
            return needLogin();
        }

        Cache.Validation v = Cache.getValidation(uuid);
        if (v == null || (v.type != Constant.SMSType.REGISTER
                && v.type != Constant.SMSType.RESET_QUESTION)){
            return fail("验证码不正确");
        }

        ScrQuestionEntity q = personalService.getByPK(ScrQuestionEntity.class, questionid);

        if (q == null){
            return fail("没有该问题");
        }

        personalService.addAnswer(user.actId, q.getQuestion(), answer);
        return success("");
    }

    @RequestMapping(value = "/personal/setPayPassword", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> payPassword(@RequestParam String password, @RequestParam String uuid,
                                         @RequestParam String token) throws Exception{
        Cache.User user = Cache.get(token);
        if (user == null){
            log.debug("token " + token + " invalid!");
            return needLogin();
        }

        Cache.Validation v = Cache.getValidation(uuid);
        if (v == null || (v.type != Constant.SMSType.REGISTER
                && v.type != Constant.SMSType.RESET_TRADE)){
            return fail("验证码不正确");
        }

        personalService.updatePayPassword(user.actId, password);
        user.isComplete = true;
        return success("");
    }

    @RequestMapping(value = "/personal/unbindPhone", method = RequestMethod.POST)
    @ResponseBody
    public Result unbindPhone(@RequestParam Long sendid, @RequestParam String code, @RequestParam String mobile,
                              @RequestParam String token) throws Exception{
        if (!userService.verifySmsCode(sendid, code, mobile, Constant.SMSType.UNBIND_MOBILE)){
            return fail("验证码不正确");
        }

        ScrAlipayEntity alipay = userService.getByPK(ScrAlipayEntity.class, getUserId(token));
        if (alipay.getMobile().equals(mobile)){
            Cache.Validation v = new Cache.Validation(mobile,
                    System.currentTimeMillis() + Constant.SMS_DEADLINE, Constant.SMSType.UNBIND_MOBILE);
            Cache.putValidation(token, v);
            return success("");
        }else{
            return fail("该手机号码不存在！");
        }
    }

    @RequestMapping(value = "/personal/bindPhone", method = RequestMethod.POST)
    @ResponseBody
    public Result bindPhone(@RequestParam Long sendid, @RequestParam String code, @RequestParam String mobile,
                              @RequestParam String token) throws Exception{
        if (!userService.verifySmsCode(sendid, code, mobile, Constant.SMSType.BIND_MOBILE)){
            return fail("验证码不正确");
        }

        Cache.Validation v = Cache.getValidation(token);
        if (v == null || v.type != Constant.SMSType.UNBIND_MOBILE){
            return fail("请先验证现在的手机号");
        }

        ScrAlipayEntity alipay = userService.getScrAlipayEntityByAccount(mobile);
        if (alipay == null){
            personalService.updateMobile(getUserId(token), mobile);

            // 删除验证缓存
            Cache.removeValidation(token);
            return success("");
        }else{
            return fail("该手机号已绑定乐汇付，请更换");
        }
    }

    @RequestMapping(value = "/personal/bindLZ", method = RequestMethod.POST)
    @ResponseBody
    public Result bindLZ(@RequestParam String account, @RequestParam String password, @RequestParam String token) throws Exception{
        AppUserEntity user = zanService.getZanUserByAccount(account);
        password = StringUtil.base64Decode(password);
        if (user == null){
            return fail("您输入的旅赞账号不存在");
        }else if (user.getLhfactid() != null && user.getLhfactid() != 0){
            return fail("该旅赞商城账号已被绑定");
        }else if (!RemoteUtil.getMd5Pwd(password, user.getSalt()).equals(user.getPassword())){
            return fail("密码错误");
        }

        SrcAuthbaseEntity auth = personalService.getAuthbaseByActid(getUserId(token));
        if (auth != null){
            if (auth.getAccounttype() != user.getAgentcategory()){
                return fail("该旅赞帐号类型和已认证账户类型不一致");
            }

            if (!auth.getCompanyname().equals(user.getCompanyname())){
                return fail("该旅赞帐号公司名称和已认证公司名称不一致");
            }
        }

        personalService.addLvZan(user, getUserId(token));

        return success("");
    }
}
